/**
 * 
 */
package dt.inlee.system.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.interceptor.validation.SkipValidation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.Validations;
import com.opensymphony.xwork2.validator.annotations.VisitorFieldValidator;

import dt.inlee.common.constant.CommonConstant;
import dt.inlee.common.exception.FrameworkException;
import dt.inlee.common.util.BaseUtil;
import dt.inlee.common.vo.PageBean;
import dt.inlee.domain.SysDictionary;
import dt.inlee.system.service.SysDictionaryService;
import dt.inlee.system.vo.SysDictionaryBean;

/**
 * @功能说明： 系统字典控制层
 * @作者： 印鲜刚
 * @创建日期： 2010-5-25 @
 */
@Scope("prototype")
@Results({@Result(name = "success", type = "json")})
@Controller("sysDictionaryAction")
public class SysDictionaryAction extends ActionSupport {
    private static final long serialVersionUID = -7085101001772580445L;
    @SuppressWarnings("unused")
    private static Logger logger = Logger.getLogger(SysDictionaryAction.class);
    @Autowired
    private SysDictionaryService sysDictionaryService;
    private List<SysDictionaryBean> sysDictionaryBeans = new ArrayList<SysDictionaryBean>();
    private SysDictionaryBean sysDictionaryBean = new SysDictionaryBean();
    private PageBean pageBean = new PageBean();
    // 处理结果
    private boolean result = false;
    private JSONObject jsonObject;

    public JSONObject getJsonObject() {
        return jsonObject;
    }

    public void setJsonObject(JSONObject jsonObject) {
        this.jsonObject = jsonObject;
    }

    public SysDictionaryBean getSysDictionaryBean() {
        return sysDictionaryBean;
    }

    @Validations(visitorFields = {@VisitorFieldValidator(message = "test", fieldName = "model", appendPrefix = false)})
    public void setSysDictionaryBean(SysDictionaryBean sysDictionaryBean) {
        this.sysDictionaryBean = sysDictionaryBean;
    }

    public PageBean getPageBean() {
        return pageBean;
    }

    public void setPageBean(PageBean pageBean) {
        this.pageBean = pageBean;
    }

    public boolean isResult() {
        return result;
    }

    public void setResult(boolean result) {
        this.result = result;
    }

    public List<SysDictionaryBean> getSysDictionaryBeans() {
        return sysDictionaryBeans;
    }

    public void setSysDictionaryBeans(List<SysDictionaryBean> sysDictionaryBeans) {
        this.sysDictionaryBeans = sysDictionaryBeans;
    }

    @Action(value = "findAllSysDictionaries", results = {@Result(type = "json")})
    @SkipValidation()
    public String findAllSysDictionaries() throws FrameworkException, Exception {
        // jqGrid查询转码-utf-8
        BaseUtil.decodeObject(this.sysDictionaryBean);
        this.pageBean.init(this.sysDictionaryService.getSysDictionaryTotalRows(this.sysDictionaryBean.getCnName(),
                this.sysDictionaryBean.getName()));
        List<SysDictionary> sysDictionaries =
                this.sysDictionaryService.findAllSysDictionaries(this.sysDictionaryBean.getCnName(),
                        this.sysDictionaryBean.getName(), this.pageBean.getCurPage(), this.pageBean.getPageSize());
        for (SysDictionary sysDictionary : sysDictionaries) {
            SysDictionaryBean bean = new SysDictionaryBean();
            BeanUtils.copyProperties(sysDictionary, bean);
            bean.setFlag(bean.getFlag().charValue() == CommonConstant.FLAG_VARIABLE ? '是' : '否');
            this.sysDictionaryBeans.add(bean);
        }
        return SUCCESS;
    }

    /**
     * 通过系统参数ID删除系统参数信息
     * 
     * @return
     * @throws FrameworkException
     */
    @Action(value = "deleteSysDictionary", results = {@Result(name = "success", type = "chain", location = "findAllSysDictionaries")})
    @SkipValidation()
    public String deleteSysDictionary() throws FrameworkException {
        this.sysDictionaryService.deleteSysDictionaryById(this.sysDictionaryBean.getDeleteIDs());
        return SUCCESS;
    }

    /**
     * 通过系统参数ID获取系统参数信息
     * 
     * @return
     * @throws FrameworkException
     */
    @Action(value = "findSysDictionary", results = {
            @Result(name = "success", location = "/page/system/sys_dictionary_modify.jsp"),
            @Result(name = "input", location = "/page/system/sys_dictionary_list.jsp")})
    @SkipValidation()
    public String findSysDictionary() throws FrameworkException, Exception {
        SysDictionary sysDictionary = this.sysDictionaryService.findSysDictionaryById(this.sysDictionaryBean.getId());
        BeanUtils.copyProperties(sysDictionary, this.sysDictionaryBean);
        return SUCCESS;
    }

    /**
     * 进入系统参数添加页面
     * 
     * @return
     * @throws FrameworkException
     */
    @Action(value = "createSysDictionary", results = @Result(name = "success", location = "/page/system/sys_dictionary_detail.jsp"))
    @SkipValidation()
    public String createSysDictionary() throws FrameworkException {
        return SUCCESS;
    }

    /**
     * 添加系统参数
     * 
     * @return
     * @throws FrameworkException
     */
    @Action(value = "saveSysDictionary", results = {
            @Result(name = "success", location = "/page/system/sys_dictionary_list.jsp"),
            @Result(name = "input", location = "/page/system/sys_dictionary_detail.jsp")})
    public String saveSysDictionary() throws FrameworkException, Exception {
        if (!BaseUtil.isEmpty(this.sysDictionaryService.findSysDictionaryByName(this.sysDictionaryBean.getName(),
                this.sysDictionaryBean.getCnName()))) {
            this.addFieldError("nameAndCnName", "已有该英文名称或中文名称!");
            return INPUT;
        }
        SysDictionary sysDictionary = new SysDictionary();
        BeanUtils.copyProperties(this.sysDictionaryBean, sysDictionary);
        this.sysDictionaryService.saveSysDictionary(sysDictionary);
        return SUCCESS;
    }

    /**
     * 修改系统参数
     * 
     * @return
     * @throws FrameworkException
     */
    @Action(value = "modifySysDictionary", results = {
            @Result(name = "success", location = "/page/system/sys_dictionary_list.jsp"),
            @Result(name = "input", location = "/page/system/sys_dictionary_modify.jsp")})
    public String modifySysDictionary() throws FrameworkException, Exception {
        if (!BaseUtil.isEmpty(this.sysDictionaryService.findSysDictionaryByIdAndName(this.sysDictionaryBean.getId(),
                this.sysDictionaryBean.getName(), this.sysDictionaryBean.getCnName()))) {
            this.addFieldError("nameAndCnName", "已有该英文名称或中文名称!");
            return INPUT;
        }
        SysDictionary sysDictionary = this.sysDictionaryService.findSysDictionaryById(this.sysDictionaryBean.getId());
        BeanUtils.copyProperties(this.sysDictionaryBean, sysDictionary);
        this.sysDictionaryService.updateSysDictionary(sysDictionary);
        return SUCCESS;
    }

    /**
     * 查询系统初始化参数列表forEasyui
     * 
     * @return
     * @throws FrameworkException
     * @throws Exception
     */
    @Action(value = "findAllSysDictionariesEasyui", results = {@Result(type = "json", name = "success", params = {
            "root", "jsonObject"})})
    @SkipValidation()
    public String findAllSysDictionariesEasyui() throws FrameworkException, Exception {
        // jqGrid查询转码-utf-8
        BaseUtil.decodeObject(this.sysDictionaryBean);
        // 行数
        int pageSize = Integer.parseInt((String) ServletActionContext.getRequest().getParameter("rows"));
        // 当前页码数
        int pageIndex = Integer.parseInt((String) ServletActionContext.getRequest().getParameter("page"));
        List<SysDictionary> sysDictionaries =
                this.sysDictionaryService.findAllSysDictionaries(this.sysDictionaryBean.getCnName(),
                        this.sysDictionaryBean.getName(), pageIndex, pageSize);
        List<SysDictionaryBean> beanList = new ArrayList<SysDictionaryBean>();
        for (SysDictionary sysDictionary : sysDictionaries) {
            SysDictionaryBean bean = new SysDictionaryBean();
            BeanUtils.copyProperties(sysDictionary, bean);
            bean.setFlag(bean.getFlag().charValue() == CommonConstant.FLAG_VARIABLE ? '是' : '否');
            beanList.add(bean);
        }
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        jsonMap.put("rows", beanList);
        jsonMap.put("total", sysDictionaries.size());
        jsonObject = JSONObject.fromObject(jsonMap);
        return SUCCESS;
    }

    /**
     * 添加系统参数
     * 
     * @return
     * @throws FrameworkException
     */
    @Action(value = "saveOrUpadateSysDictionariesEasyui", results = {@Result(type = "json", name = "success", params = {
            "root", "jsonObject"})})
    @SkipValidation()
    public String saveOrUpadateSysDictionariesEasyui() throws FrameworkException, Exception {
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        jsonMap.put("flag", false);
        if (!BaseUtil.isEmpty(this.sysDictionaryService.findSysDictionaryByName(this.sysDictionaryBean.getName(),
                this.sysDictionaryBean.getCnName()))) {
            jsonMap.put("content", "已有该英文名称或中文名称!");
        } else {
            String id = this.sysDictionaryBean.getId();
            SysDictionary sysDictionary = null;
            if (BaseUtil.isEmpty(id)) {
                sysDictionary = new SysDictionary();
                sysDictionary.setCnName(sysDictionaryBean.getCnName());
                sysDictionary.setFlag(sysDictionaryBean.getFlag());
                sysDictionary.setName(sysDictionaryBean.getName());
                sysDictionary.setRemark(sysDictionaryBean.getRemark());
                sysDictionary.setValue(sysDictionaryBean.getValue());
                this.sysDictionaryService.saveSysDictionary(sysDictionary);
            } else {
                sysDictionary = this.sysDictionaryService.findSysDictionaryById(id);
                sysDictionary.setCnName(sysDictionaryBean.getCnName());
                sysDictionary.setFlag(sysDictionaryBean.getFlag());
                sysDictionary.setName(sysDictionaryBean.getName());
                sysDictionary.setRemark(sysDictionaryBean.getRemark());
                sysDictionary.setValue(sysDictionaryBean.getValue());
                this.sysDictionaryService.updateSysDictionary(sysDictionary);
            }
            jsonMap.put("flag", true);
        }
        jsonObject = JSONObject.fromObject(jsonMap);
        return SUCCESS;
    }

    /**
     * 通过系统参数ID删除系统参数信息
     * 
     * @return
     * @throws FrameworkException
     */
    @Action(value = "deleteSysDictionaryEasyui", results = {@Result(type = "json", name = "success", params = {"root",
            "jsonObject"})})
    @SkipValidation()
    public String deleteSysDictionaryEasyui() throws FrameworkException {
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        jsonMap.put("flag", false);
        if (!BaseUtil.isEmpty(this.sysDictionaryBean.getDeleteIDs())) {
            String[] arrayIds = this.sysDictionaryBean.getDeleteIDs().split(",");
            for (String id : arrayIds) {
                this.sysDictionaryService.deleteSysDictionaryById(id);
            }
            jsonMap.put("flag", true);
        }
        jsonObject = JSONObject.fromObject(jsonMap);
        return SUCCESS;
    }
}
